
package org.midi.util;

import java.io.*;

/**
 * Works like ByteArrayOutputStream, but uses a user-supplied byte array.
 * Writing too many bytes will throw an IOException.
 */
public class FixedByteArrayOutputStream extends OutputStream {

	private final byte[] buffer;
	private final int start;
	private final int end;
	private int pos;

	public FixedByteArrayOutputStream(byte[] buffer) {
		this(buffer, 0, buffer.length);
	}

	public FixedByteArrayOutputStream(byte[] buffer, int off, int len) {
		this.buffer = buffer;
		this.start = off;
		this.end = off + len;
		if (start < 0 || start > end || end > buffer.length) {
			throw new IllegalArgumentException("The specified offset and/or length are not valid for the specified byte array.");
		}
		pos = start;
	}

	public void write(int b) throws IOException {
		if (pos >= end) throw new IOException("Can't write any more. Fixed-length buffer is full.");
		buffer[pos++] = (byte)b;
	}

	public void write(byte[] b) throws IOException {
		write(b, 0, b.length);
	}

	public void write(byte[] b, int off, int len) throws IOException {
		if (pos + len >= end) throw new IOException("Can't write " + len + " bytes, not enough space left.");
		System.arraycopy(b, off, buffer, pos, len);
		pos += len;
	}

	/** Returns the number of bytes written. */
	public int count() {
		return pos - start;
	}

	/** Copies the written section of the buffer to a new array, and returns it. */
	public byte[] toByteArray() {
		int count = count();
		byte[] result = new byte[count];
		System.arraycopy(buffer, start, result, 0, count);
		return result;
	}
}
